import datetime
import json

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.views import View
from django.conf import settings

from fdfs_client.client import Fdfs_client
from pygments.formatters import img


from leisurely.utils import get_house_count_date
from six_it.models import User, Area, House, Order


class ChangeUsernameView(View):
    """修改用户名"""

    def put(self, request):
        """
        修改用户名
        :param request:
        :return:
        """
        # 获取前端数据
        data_dict = json.loads(request.body)
        new_name = data_dict.get('name')
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({
                "errno": "4101",
                "errmsg": "用户未登录"
            })

        # 验证数据
        if not all([new_name]):
            return JsonResponse({
                "errno": "4002",
                "errmsg": "无数据"
            })

        # 读取数据库修改密码
        User.objects.filter(id=user.id).update(username=new_name)

        # 返回结果
        return JsonResponse({
            "errno": "0",
            "errmsg": "修改成功"
        })


class AreasListView(View):

    def get(self, request):
        """城区列表"""

        # 获取数据库数据
        areas = Area.objects.all()
        data_list = list()
        for area in areas:
            data_list.append({
                'aid': area.id,
                'aname': area.name,
            })

        # 返回结果
        response = JsonResponse({
            "errmsg": "获取成功",
            "errno": "0",
            "data": data_list,
        })
        return response


class MyListView(View):
    '''我的房屋列表'''

    def get(self, request):

        # 获取用户
        user = request.user
        user_id = user.id
        # 登录用户
        if user.is_authenticated:
            # 查询数据库
            houses = House.objects.filter(user_id=user_id)
            houses_list = []
            for house in houses:
                house_dict = {
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.create_time.strftime("%Y-%m-%d"),
                    "house_id": house.id,
                    "img_url": house.index_image_url if house.index_image_url else "",
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": 'http://127.0.0.1:8888/' + str(house.user.avatar) if 'http://127.0.0.1:8888/' + str(
                        house.user.avatar) else "",
                }
                houses_list.append(house_dict)

            # 构建返回结果
            return JsonResponse({
                "data": {
                    "houses": houses_list
                },
                "errmsg": "ok",
                "errno": "0"
            })

        # 未登录用户
        else:
            return JsonResponse({'code': 400, 'errmsg': '用户未登录'}, status=400)


# class HoushListView(View):
#     '''房屋数据搜索'''
#

#     def get(self,request):
#
#         # 获取前端数据
#         aid = request.GET.get('aid')
#         sd = request.GET.get('sd')
#         ed = request.GET.get('ed')
#         # 排序方式
#         sk = request.GET.get('sk')
#         p = request.GET.get('p',default = 1)
#
#         # 筛选条件
#         filters = {}
#         # 排序
#         sk_dict = {'booking':"-order_count","price-inc":"price","price-des":"-price"}
#         # 判断地区id
#         if aid:
#             filters["area"] = aid
#         # 判断时间
#         try:
#             if not (sd and ed) or not sd or not ed :
#                 start = datetime.datetime.today()
#                 end = start + datetime.timedelta(days=15)
#                 start_date = datetime.datetime.date(start)
#                 end_date = datetime.datetime.date(end)
#                 filters["min_days__lte"]=15
#                 filters["max_days__gte"]=15
#                 # conflict_order = Order.objects.filter(end_date__gt=start_date,begin_date__lt=end_date)
#             else:
#                 start_date = datetime.datetime.strptime(sd, '%Y-%m-%d')
#                 end_date = datetime.datetime.strptime(ed, '%Y-%m-%d')
#                 # 入住时间晚于结束时间
#                 if start_date>end_date:
#                     start_date,end_date = end_date,start_date
#             conflict_order = Order.objects.filter(begin_date__lt=end_date, end_date__gt=start_date)
#
#         except Exception as e:
#             return JsonResponse({"errno": "4103", "errmsg": "错误"})
#
#         # 将冲突订单的房屋id加入冲突列表
#         conflict_house_id = []
#         for order in conflict_order:
#             conflict_house_id.append(order.house_id)
#         # 查询出来的房屋列表过滤冲突订单中的房屋id
#         if conflict_house_id:
#             filters["id__in"] = conflict_house_id
#
#         # 排序方式{'min_days__lte': 15, 'max_days__gte': 15}
#         houses_query = House.objects.filter(**filters).order_by(sk_dict.get(sk,"-create_time"))
#         paginator = Paginator(houses_query, 5)
#         # 获取当前页对象
#         page_houses = paginator.page(p)
#         # 获取总页数
#         total_page = paginator.num_pages
#
#         houses = []
#         for house in page_houses:
#             count = get_house_count_date(house,sd,ed)
#             # 剩余房间数量为0,
#             if count == 0:
#                 continue
#             house_dict = {
#                 "address": house.address,
#                 "area_name": house.area.name,
#                 "ctime": house.create_time.strftime("%Y-%m-%d"),
#                 "house_id": house.id,
#                 "img_url": 'http://127.0.0.1:8888/'+house.index_image_url if 'http://127.0.0.1:8888/'+house.index_image_url else "",
#                 "order_count": house.order_count,
#                 "price": house.price,
#                 "room_count": count,
#                 "title": house.title,
#                 "user_avatar": 'http://127.0.0.1:8888/'+str(house.user.avatar) if 'http://127.0.0.1:8888/'+str(house.user.avatar) else "",
#             }
#             houses.append(house_dict)
#
#         data = {
#             "total_page": total_page,
#             "houses": houses
#         }
#         return JsonResponse({"errno": "0", "errmsg": "OK", "data": data})




class UserInfoView(View):
    """用户个人中心"""

    def get(self, request):
        # 1、获取数据
        user = request.user
        url = user.avatar
        return JsonResponse({
            "data": {
                "avatar": 'http://127.0.0.1:8888/' + str(url),
                "create_time": user.date_joined,
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id
            },
            "errmsg": "OK",
            "errno": "0"
        })


class AvatarView(View):
    """上传头像"""

    def post(self, request):
        # 接收参数
        avatar = request.FILES.get("avatar")
        if not avatar:
            return JsonResponse({"errno": 4103, "errmsg": "参数错误"})

        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        # 读取出文件对象的二进制数据
        result = client.upload_appender_by_buffer(avatar.read())
        if result.get('Status') != 'Upload successed.':
            return JsonResponse({"errno": 4103, "errmsg": "上传图片失败"})
        try:
            url = result.get('Remote file_id')
        except Exception as e:
            return JsonResponse({"errno": 4103, "errmsg": "上传图片失败"})
        user = request.user
        user.avatar = url
        user.save()
        return JsonResponse({"data": {'avatar_url': 'http://127.0.0.1:8888/' + url},
                             "errno": 0,
                             "errmsg": "上传图片成功"})
